package ConexaoBanco;

import java.sql.*;


	public class RepositorioBancoDados {
		
		private static final String DRIVER = "org.hsqldb.jdbcDriver";
		private static final String URL = "jdbc:hsqldb:hsql://localhost/EscapeBD";
		private static final String USUARIO = "sa";
		private static final String SENHA = "";
		
		protected Connection getConnection() {
			try {
				Class.forName(DRIVER);
				return DriverManager.getConnection(URL, USUARIO, SENHA);

			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		}

		protected void close(Connection connection) {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					throw new RuntimeException(e.getMessage()); 
				}
			}
		}

		protected void close(Statement statement) {
			if (statement != null) {
				try {
					close(statement.getConnection());
					statement.close();
				} catch (SQLException e) {
					throw new RuntimeException(e.getMessage());
				}
			}
		}

		protected void close(ResultSet resultSet) {
			if (resultSet != null) {
				try {
					resultSet.close();
					close(resultSet.getStatement());
				} catch (SQLException e) {
					throw new RuntimeException(e.getMessage());
				}
			}
		}
		
		/**
		 * Utilizado para comandos SQL de update, insert ou delete
		 * 
		 * @param sql
		 */
		protected void executarUpdate(String sql) {
			Statement stmt = null;
			Connection con = null;
			try {
				System.out.println("Comando Executado: " + sql);
				con = getConnection();
				stmt = con.createStatement();
				stmt.executeUpdate(sql);
			} catch (SQLException e) {
				throw new RuntimeException(e.getMessage());
			} finally {
				close(stmt);
			}
		}
		
		/**
		 * Utilizado para executar comandos SQL de consulta (Select) 
		 * 
		 * @param sql
		 * @return
		 */
		protected ResultSet executarConsulta(String sql) {
			Statement stmt = null;
			Connection con = null;
			try {
				//System.out.println("Consulta Executada: " + sql);
				con = getConnection();
				stmt = con.createStatement();
				return stmt.executeQuery(sql);
			} catch (SQLException e) {
				throw new RuntimeException(e.getMessage());
			} 
		}
	}
